import globalData from "./globalData.js"
import {
	getAppId
} from "./platform.js"
import {
	sha256
} from 'js-sha256'
import {
	baseUrl,
	api_url,
	APP_APPID
} from "./constant"
import {
	goLogin
} from "@/main.js"
import {
	getUserId,
	getShowLoading,
	getHideLoading,
	getZWZUserDetail,
	saveUserId,
	saveZWZUserDetail,
} from './index.js'
/**
 * 接口调用函数
 * @param {string} url:接口路径
 * @param {Object} data:接口参数
 * @param {string} method:默认GET请求
 * @param {boolean} addUid : 是否需要把uid拼上去。注：目前只适用于将uid拼在链接上，而非放在data中，同时如果需要拼接多个参数的话，目前也不支持在这里进行统一拼接
 * @param {boolean} loading : 是否需要页面加载效果
 * @param {Object} customizeHeaderObj : 自定义请求头
 */
const request = (
	url,
	data,
	method = "GET",
	addUid = true,
	loading = false,
	customizeHeaderObj = {},
	arrIs = false,
	isToastErrMsg = true
) => {
	let requestUrl = url
	// #ifdef H5 || APP-PLUS
	if (addUid) {
		let uid = getUserId()
		if (!uid) {
			// goLogin();
			// return Promise.reject('未登录')
		} else {
			if (method.toUpperCase() === "GET") {
				if (url.includes("?")) {
					requestUrl = `${url}&uid=${uid}`
				} else {
					requestUrl = `${url}?uid=${uid}`
				}
			} else if (method.toUpperCase() === "POST") {
				data.uid = getUserId();
			}
		}
	}
	// #endif

	// #ifndef H5 || APP-PLUS
	if (addUid) {
		let uid = getUserId()
		if (!uid) {
			// goLogin();
			// return Promise.reject('未登录')
		} else {
			if (method.toUpperCase() === "GET") {
				if (url.includes("?")) {
					requestUrl = `${url}&uid=${uid}`
				} else {
					requestUrl = `${url}?uid=${uid}`
				}
			} else if (method.toUpperCase() === "POST") {
				data.uid = getUserId();
			}
		}
	}
	// #endif



	// console.log('发起请求拼接后：'+requestUrl)
	const infoObj = globalData.infoByAppId || {}
	const appDescObj = infoObj[getAppId()] || {}
	const channelid = appDescObj.channelId
	let rentchannelid = uni.getStorageSync("pid")
	if (rentchannelid) customizeHeaderObj.rentchannelid = rentchannelid

	let token = getZWZUserDetail().token
	if (token) customizeHeaderObj.token = token
	let uid = getUserId()
	if (uid) customizeHeaderObj.uid = uid

	// let isauth = uni.getStorageSync("auth")
	// if (isauth) customizeHeaderObj.isauth = isauth

	// 请求认证签名
	let timestamp = new Date().getTime();
	let appid = "hy_60b60e38711abe9f";
	let appSecret = "6160aa57cd9a3dbc8229ce92f9e41810b8104f6518f740f9";
	let sourceStr = appid + "," + timestamp + "," + appSecret;
	// let sign = sha256(sourceStr);
	customizeHeaderObj.appids = appid
	customizeHeaderObj.timestamps = timestamp
	customizeHeaderObj.signs = sha256(sourceStr);
	customizeHeaderObj.appletappid = APP_APPID;


	let appletappid = APP_APPID
	if (appletappid) customizeHeaderObj.appletappid = APP_APPID
	let myrequest = new Promise((resolve, reject) => {
		loading && getShowLoading({
			content: "加载中..."
		})
		uni.request({
			url: /http/.test(requestUrl) ? requestUrl : `${baseUrl}${requestUrl}`,
			method: method,
			header: {
				channelid,
				...customizeHeaderObj,
			},
			// data: {
			// 	...data,
			// 	channelId: channelid,
			// },
			data: arrIs ? data : {
				...data,
				channelId: channelid,
			},
			success: (res) => {
				if (res.respCode === 8003) {
					uni.switchTab({
						url: '/pages/index/index'
					});
					return reject(res.data || res.msg)
				}
				if (
					res.data &&
					res.data.responseType !== "SUCCESS" &&
					res.data.errorMessage
				) {
					if (res.data.errorMessage && res.data.errorMessage.length > 1) {
						let reg = /(.*\/)*([^.]+).*err_/g
						let msg = res.data.errorMessage.replace(reg, "")
						if (isToastErrMsg) {
							uni.showToast({
								icon: "none",
								title: msg,
							})
						}

						// getErrText()
					}
					loading && getHideLoading()
					//console.log('test----------')
					return reject(res.data)
				} else {
					// saveZWZUserDetail(undefined);
					loading && getHideLoading()
					// return resolve(res.data)

					if (res.data.code && res.data.code == 500) {
						if (res.data.msg && res.data.msg.indexOf('Token失效') != -1) {
							console.log('去重新登录');
							uni.showToast({
								title: '登录已过期，请重新登录！',
								icon: 'none',
								duration: 1000
							});
							uni.clearStorageSync();
							saveUserId(undefined);
							saveZWZUserDetail(undefined);
							let timer1 = null
							timer1 = setTimeout(() => {
								uni.hideLoading()
								uni.reLaunch({
									url: `/pagesOther/phone_login/phone_login`
								});
								clearTimeout(timer1);
								timer1 = null
							}, 1000); // 延迟0.5秒
						} else {
							return resolve(res.data)
						}
					} else {
						return resolve(res.data)
					}

				}
			},
			fail: (res) => {

				console.log('请求失败：' + baseUrl + requestUrl, res)
				loading && getHideLoading()

				//     uni.showToast({
				//       title: res.data.message,
				// icon:"none"
				//     })

			},
		})
	})
	return myrequest
}
export default request;